package com.zqg8512.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class JsonUtils {
    
    /** 默认舍弃值为null的字段 */
    private static final JsonInclude.Include INCLUDE = JsonInclude.Include.NON_NULL;
    
    /**
     *把 object 转换为 JsonString
     * @param obj 
     * @return
     * @throws Exception
     */
    public static String object2JsonString(Object obj){
        if(obj == null) {
            return "";
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(INCLUDE);
            String json = mapper.writeValueAsString(obj);
            return json;
        } catch (Exception e) {
            return "";
        }
    }


    /**
     *
     * @return
     * @throws Exception
     */
    public static <T> T json2Obj(String json,Class<T> type){
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(INCLUDE);
            T t = JSON.parseObject(json, type);
            return t;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     *  资源文件json 转 对象
     * @param path resource目录下的文件路径
     * @param type 转换的类型
     * @param <T> 返回类型
     * @return
     * @throws IOException
     */
    public static <T> T json2Object(String path, Class<T> type) throws IOException {
        ClassPathResource resource = new ClassPathResource(path);
        if (resource.exists()) {
            return JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, type,
                    // 自动关闭流
                    Feature.AutoCloseSource,
                    // 允许注释
                    Feature.AllowComment,
                    // 允许单引号
                    Feature.AllowSingleQuotes,
                    // 使用 Big decimal
                    Feature.UseBigDecimal);
        } else {
            throw new IOException();
        }
    }
}